//
// Created by 大土豆 on 2019-08-21.
// Copyright (c) 2019 Mac. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

class GTVideoPlayer: NSObject {

    private override init() {

    }
    static let shared = GTVideoPlayer()

    private var videoItem: AVPlayerItem?=nil
    private var avPlayer: AVPlayer?=nil
    private var playerLayer: AVPlayerLayer?=nil

    public func playVideoWithUrl(videoUrl: String, attchView: UIView) {
        stopPlay()

        //这边初始化一定得注意，和objective-c的差别，之前初始化错了，导致没法播放
        let videoUrl = URL.init(string: videoUrl)
        let asset = AVAsset.init(url: videoUrl!)
        videoItem = AVPlayerItem.init(asset: asset)
//    监听视频资源状态
        videoItem!.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
        //    监听视频缓冲进度
        videoItem!.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.new, context: nil)

        //    需要在状态变化后获取时间
        let duration = videoItem!.duration
        let videoDuration = CMTimeGetSeconds(duration)

        avPlayer = AVPlayer.init(playerItem: videoItem)
//        闭包的写法
        avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1), queue: DispatchQueue.main, using:
        { (cmtime: CMTime) -> Void in
            NSLog("播放进度：%s", CMTimeGetSeconds(cmtime));
        })

        playerLayer = AVPlayerLayer.init(player: avPlayer)
        playerLayer?.frame = attchView.bounds
        attchView.layer.addSublayer(playerLayer!)
        
        NotificationCenter.default.addObserver(self, selector: #selector(handlePlayEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
    }

    private func stopPlay() {
        //    移除监听
        NotificationCenter.default.removeObserver(self)
        videoItem?.removeObserver(self, forKeyPath: "status")
        videoItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")

//    销毁播放器
        playerLayer?.removeFromSuperlayer()
        //Swfit中的nil和objective-c的nil不一样，不能这样赋值
//        videoItem = nil;
//        avPlayer = nil;
    }

    @objc func handlePlayEnd() {
        avPlayer!.seek(to: CMTime(value: 0, timescale: 1))
        avPlayer!.play()
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if(keyPath == "status"){
            if let temp = change![NSKeyValueChangeKey.newKey] as? Int{
                if(temp == AVPlayerItemStatus.readyToPlay.rawValue){
                    avPlayer?.play()
                }else{
                    //监控错误
                }
            }
        }else if(keyPath == "loadedTimeRanges"){
            //缓冲进度监听，nslog不能打印Swift包装类型的对象，只能用print打印
            print("缓冲:%s", change![NSKeyValueChangeKey.newKey]!)
        }
        
    }

}

